<template>
  <div class="flexContent">
    <div class="searchBox">
      <!-- 商品销售统计报表 -->
      <el-form class="demo-form-inline" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="门店">
                  <el-select v-model="sForm.storeId" @click.native="getShopAllList" filterable clearable
                    popper-class="eloption" style="width: 95%;" placeholder="请选择">
                    <el-option v-for="shop in shopListTwo" :key="shop.id" :value="shop.id" :label="shop.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品">
                  <el-input v-clearEmoji v-model.trim="sForm.name" size="small" clearable style="width: 95%;"
                    placeholder="请输入" @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品类型">
                  <el-select v-model="sForm.type" style="width: 95%;" placeholder="请选择商品类型" clearable>
                    <el-option value="0" label="标品" />
                    <el-option value="1" label="自营" />
                    <el-option value="2" label="非标" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" v-has="'goodsSellReport_export'" @click="exportFn">导出</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium" align="center">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="commodityName" title="商品名称"
            :min-width="elTableAdaptationWidth('commodityName', tableData)" />
          <vxe-column field="barcode" title="商品条码" :min-width="elTableAdaptationWidth('barcode', tableData)" />
          <vxe-column field="type" title="商品类型" :min-width="elTableAdaptationWidth('type', tableData)" />
          <vxe-column field="salesNum" title="累计销量" min-width="150">
            <template #header="{ column }">
              <div style="display: flex;justify-content: center;">
                <span>累计销量</span>
                <span style="display: flex;flex-direction: column;">
                  <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                    :class="sort === '1' ? 'iconClsActived' : ''" @click="sortFn('1')"></i>
                  <i style="cursor: pointer;transform: translateY(-5px);" :class="sort === '0' ? 'iconClsActived' : ''"
                    class="el-icon-caret-bottom iconCls" @click="sortFn('0')"></i>
                </span>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="salesVolume" title="累计销售额" min-width="150">
            <template #header="{ column }">
              <div style="display: flex;justify-content: center;">
                <span>累计销售额</span>
                <span style="display: flex;flex-direction: column;">
                  <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                    :class="sort === '3' ? 'iconClsActived' : ''" @click="sortFn('3')"></i>
                  <i style="cursor: pointer;transform: translateY(-5px);" :class="sort === '2' ? 'iconClsActived' : ''"
                    class="el-icon-caret-bottom iconCls" @click="sortFn('2')"></i>
                </span>
              </div>
            </template>
          </vxe-column>
          <vxe-column v-if="$showFn(['goodsSellReport_detail'])" fixed="right" width="100" title="操作">
            <template v-slot="{ row }">
              <el-button type="text" style="margin-right: 5px" @click.stop="detail(row)"
                v-has="'goodsSellReport_detail'">详情</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,-> , sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import { getShopEasy } from "@/api/shop";
import { reqSellStatisticList, reqExportSell } from "@/api/report";
export default {
  name: "GoodsSellReport",
  data() {
    return {
      sort: '0',
      shopListTwo: [],
      sForm: {
        storeId: '',
        name: '',
        type: ''
      },

      tableData: [],
      firstSupplierList: [],
      isSearch: false,
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      allDataArr: [],
    };
  },
  created() {
    this.getShopAllList();
    this.getSellStatisticList();
  },
  activated() {
    this.isSearch = true
    this.getSellStatisticList();
  },
  methods: {
    async getShopAllList() {
      const res = await getShopEasy()
      if (res.code === 200) {
        this.shopListTwo = res.data.store;
      }
    },
    async getSellStatisticList() {
      if (!this.isSearch) {
        this.sForm = {
          storeId: '',
          type: '',
          name: ''
        }
      }
      const res = await reqSellStatisticList({
        ...this.page,
        ...this.sForm,
        sort: this.sort
      });
      if (res.code === 200) {
        const result = res.data;
        this.tableData = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        const $table = this.$refs.xTable1
        $table.loadData(this.tableData);
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getSellStatisticList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.getSellStatisticList();
    },
    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = true;
      this.getSellStatisticList();
    },
    resetFn() {

      this.sForm = {
        storeId: '',
        type: '',
        name: '',
      }
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = false;
      this.getSellStatisticList();
    },
    sortFn(sort) {
      console.log('sort', sort);
      this.sort = sort
      this.getSellStatisticList();
    },
    async exportFn() {
      this.$confirm('确认导出数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (!this.isSearch) {
          this.sForm = {
            storeId: '',
            name: '',
            type: '',
          }
        }
        let response = await reqExportSell({ ...this.sForm })
        let res = null;
        if (response.data.type === "application/json") {
          const reader = new FileReader();  //创建一个FileReader实例
          reader.readAsText(response.data, 'utf-8'); //读取文件,结果用字符串形式表示
          reader.onload = () => {//读取完成后,**获取reader.result**
            res = JSON.parse(reader.result)
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
        } else {
          const fileName = decodeURIComponent(response.headers["content-disposition"].split(";")[1].split("''")[1]);
          FileSaver.saveAs(response.data, fileName);
        }
      })
    },
    detail(row) {
      if (!this.isSearch) {
        this.sForm = {
          storeId: '',
          name: '',
          type: '',
        }
      }
      if (row.type === '标品') {
        this.$router.push({
          path: '/reportInfo/goodsSellReportDetail',
          query: {
            id: row.id,
            type: 0,
          }
        })
      } else if (row.type === '非标') {
        this.$router.push({
          path: '/reportInfo/goodsSellReportDetail',
          query: {
            type: 2,
            name: row.commodityName
          }
        })
      } else if (row.type === '自营') {
        this.$router.push({
          path: '/reportInfo/goodsSellReportDetail',
          query: {
            type: 1,
            barcode: row.barcode
          }
        })
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.iconCls:hover {
  color: #ee2b08 !important;
}

.iconClsActived {
  color: #ee2b08 !important;
}

.txtBox {
  padding-left: 20px;
  margin-bottom: 30px;

}

.btnBOX {
  text-align: center;
}
</style>
